//
//  PPAlbumTagsManager.m
//  pickpic
//
//  Created by Jinxiao on 9/16/16.
//  Copyright © 2016 MicroDream. All rights reserved.
//

#import "PPAlbumTagsManager.h"

#import "PPNetworkService.h"

#import "PPAlbumHotTagModel.h"
#import "PPAlbumCustomTagModel.h"

@implementation PPAlbumTagsManager

+ (instancetype)sharedInstance
{
    static id instance;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        instance = self.new;
    });
    return instance;
}

- (void)fetchHotTags {

    [PPNetworkService fetchHotTagsWithCallback:^(id data, NSError *error) {

        if(error == nil) {
            [[PPAlbumHotTagModel all] makeObjectsPerformSelector:@selector(delete)];

            NSArray *tags = [data validArrayForKey:@"tags"];
            [tags enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                NSNumber *tagID = [obj validNumberForKey:@"tagid"];
                PPAlbumHotTagModel *tag = [PPAlbumHotTagModel existingAlbumHotTagForTagID:tagID];
                tag.index = [obj validNumberForKey:@"index"];
                tag.name = [obj validStringForKey:@"name"];
                tag.pinyin = [obj validStringForKey:@"pinyin"];
            }];

            [[NSManagedObjectContext threadObjectContext] saveContext];
        }

    }];

}

- (void)fetchCustomTags {

    [PPNetworkService fetchUserCreatedTagsWithCallback:^(id data, NSError *error) {

        if(error == nil) {
            [[PPAlbumCustomTagModel all] makeObjectsPerformSelector:@selector(delete)];

            NSArray *tags = [data validArrayForKey:@"tags"];
            [tags enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                NSNumber *tagID = [obj validNumberForKey:@"tagid"];
                PPAlbumCustomTagModel *tag = [PPAlbumCustomTagModel existingAlbumCustomTagForTagID:tagID];
                tag.index = [obj validNumberForKey:@"index"];
                tag.name = [obj validStringForKey:@"name"];
                tag.pinyin = [obj validStringForKey:@"pinyin"];
            }];

            [[NSManagedObjectContext threadObjectContext] saveContext];
        }
        
    }];

}

@end
